﻿#include"XQHttpHeadRecv.h"
#include<QDebug>
XQHttpHeadRecv::XQHttpHeadRecv()
{
	init_header();
}

XQHttpHeadRecv::XQHttpHeadRecv(const QString& header)
{
	init_header();
	setHeader(header);
}

void XQHttpHeadRecv::setHeadType(XQHttpHeadType headType)
{
	m_headType = headType;
}

void XQHttpHeadRecv::setHeader(const QString& header)
{
	auto list = header.split("\r\n");
	if (list.isEmpty())
		return;
	clear();
	if (list[0].startsWith("HTTP"))
	{//http开头证明是接收到的报文
		setHeadType(XQHttpHeadType::recv);
		auto state = list[0].split(" ");
		if (state.size() > 1)
			m_state = state[1].toInt();//获取状态码
	}
	else
	{
		setHeadType(XQHttpHeadType::send);
	}
	for (size_t i = 1; i < list.size(); i++)
	{
		auto& str = list[i];
		int nSel = str.indexOf(":");
		if (nSel == -1)
			continue;
		auto key = str.left(nSel).trimmed();
		auto vlaue = str.mid(nSel+1).trimmed();
		this->header.insert(key,vlaue);
		/*qInfo() << key << vlaue;*/
	}
	/*qInfo() << list;*/
}

void XQHttpHeadRecv::setResPath(const QString& path)
{
	m_resPath = path;
}

void XQHttpHeadRecv::setMethod(XQHttpRequestType q)
{
	if (q == XQHttpRequestType::GET)
	{
		m_method = "GET";
	}
	else if (q == XQHttpRequestType::POST)
	{
		m_method = "POST";
	}
}

void XQHttpHeadRecv::setHost(const QString& host)
{
	header["Host"] = host;
}

void XQHttpHeadRecv::setHost(const QString& host, const int port)
{
	setHost(host);
	setPort(port);
}

void XQHttpHeadRecv::setPort(const int port)
{
	this->m_port = port;
}

void XQHttpHeadRecv::setReferer(const QString& ref)
{
	header["Referer"] = ref;
}

void XQHttpHeadRecv::setCookie(const QString& cookie)
{
	header["Cookie"] = cookie;
}

void XQHttpHeadRecv::init_header()
{
	header["Host"] = "127.0.0.1";
	header["Connection"] = "keep-alive";
	//header_recv["Connection"] = "close";
	header["User-Agent"] = "Mozilla/5.0";
	header["Accept"] = "*/*";
	//header["Referer"] = "";
	header["Accept-Encoding"] = "deflate";
	header["Accept-Language"] = "zh-CN,zh;q=0.9";
	//header["Cookie"] = "";
	header["Accept"] = "*/*";
	header["AcceptEncoding"] = "deflate";
	/*AcceptLanguage = "zh-CN,zh;q=0.9";
	Connection = "close";
	UserAgent = "Mozilla/5.0";*/
}

void XQHttpHeadRecv::clear()
{
	header.clear();
}

bool XQHttpHeadRecv::isEmpty() const
{
	return header.isEmpty();
}

XQHttpHeadType XQHttpHeadRecv::headType() const
{
	return m_headType;
}

int XQHttpHeadRecv::state() const
{
	return m_state;
}

QString XQHttpHeadRecv::host()
{
	return header["Host"];
}

const int XQHttpHeadRecv::port()
{
	return m_port;
}

QString XQHttpHeadRecv::getResPath()
{
	return m_resPath;
}

qint64 XQHttpHeadRecv::ContentLength()
{
	auto text = header.value("Content-Length");
	if (text.isEmpty())
		return -1;
	return text.toULongLong();
}
